<template>
  <div
    v-loading.fullscreen.lock="loading"
    :element-loading-text="$t('loading')"
    :class="['aui-wrapper', { 'aui-sidebar--fold': $store.state.sidebarFold }]"
  >
    <template v-if="!loading">
      <main-navbar />
      <main-sidebar v-if="show" />
      <div class="aui-content__wrapper">
        <main-content v-if="!$store.state.contentIsNeedRefresh" />
      </div>
      <main-theme-tools />
    </template>
  </div>
</template>

<script>
import MainNavbar from "./main-navbar";
import MainSidebar from "./main-sidebar";
import MainContent from "./main-content";
import MainThemeTools from "./main-theme-tools";
import debounce from "lodash/debounce";
import { isURL } from "@/utils/validate";
import Router from "vue-router";
export default {
  provide() {
    return {
      // 刷新
      refresh() {
        this.$store.state.contentIsNeedRefresh = true;
        this.$nextTick(() => {
          this.$store.state.contentIsNeedRefresh = false;
        });
      },
    };
  },
  data() {
    return {
      loading: true,
      idName: "",
      show: false,
    };
  },
  components: {
    MainNavbar,
    MainSidebar,
    MainContent,
    MainThemeTools,
  },
  watch: {
    $route: "routeHandle",
  },
  created() {
    this.windowResizeHandle();
    this.routeHandle(this.$route);
    Promise.all([this.getId(), this.getUserInfo()]).then(() => {
      this.loading = false;
    });
  },
  methods: {
    // 窗口改变大小
    windowResizeHandle() {
      this.$store.state.sidebarFold =
        document.documentElement["clientWidth"] <= 992 || false;
      window.addEventListener(
        "resize",
        debounce(() => {
          this.$store.state.sidebarFold =
            document.documentElement["clientWidth"] <= 992 || false;
        }, 150)
      );
    },
    // 路由, 监听
    routeHandle(route) {
      if (!route.meta.isTab) {
        return false;
      }
      let tab = {};
      let routeName = route.name;
      let routeMeta = route.meta;
      if (route.name === "iframe") {
        let url = route.query.url || "";
        if (!isURL(url)) {
          return false;
        }
        let key = route.query.key || new Date().getTime();
        routeName = `${routeName}_${key}`;
        routeMeta.title = key.toString();
        routeMeta.menuId = route.query.menuId || "";
        routeMeta.iframeURL = url;
      }
      tab = this.$store.state.contentTabs.filter(
        (item) => item.name === routeName
      )[0];
      if (!tab) {
        tab = {
          ...window.SITE_CONFIG["contentTabDefault"],
          ...routeMeta,
          name: routeName,
          params: {
            ...route.params,
          },
          query: {
            ...route.query,
          },
        };
        this.$store.state.contentTabs =
          this.$store.state.contentTabs.concat(tab);
      }
      this.$store.state.sidebarMenuActiveName = tab.menuId;
      this.$store.state.contentTabsActiveName = tab.name;
    },
    async getId() {
      if (this.$store.state.user.type == "1") {
        await this.getHotelId(); //民宿ids
      } else if (this.$store.state.user.type == "2") {
        await this.getMerchantId(); //商户ids
      }
      this.getPermissions();
      this.getNav();
    },
    getNav() {
      // 获取菜单列表, 添加并全局变量保存
      this.$http
        .get("/sys/menu/nav")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            Vue.prototype.$message.error(res.msg);
          }
          localStorage.setItem("navListArr", JSON.stringify(res.data));
          if (res.data[this.idName]) {
            window.SITE_CONFIG["menuList"] = res.data[this.idName];
          } else {
            window.SITE_CONFIG["menuList"] = res.data[-1];
          }
          localStorage.setItem(
            "currentMenuList",
            JSON.stringify(window.SITE_CONFIG["menuList"])
          );
          this.fnAddDynamicMenuRoutes(window.SITE_CONFIG["menuList"]);
        })
        .catch(() => {});
    },
    getHotelId() {
      return new Promise((resolve, reject) => {
        this.$http.get("/hotel/homestay/getUserHomestayList").then((res) => {
          if (res.data.code == 0) {
            if (res.data.data.length > 0) {
              this.$store.state.user.homestayId = res.data.data[0].id || "";
              this.$store.state.user.homestayName = res.data.data[0].name || "";
              localStorage.setItem(
                "ss_merchantCategory",
                res.data.data[0].merchantCategory || ""
              );
              this.idName = res.data.data[0].id;
            } else {
              this.$store.state.user.homestayId = "";
              this.$store.state.user.homestayName = "";
              localStorage.setItem("ss_merchantCategory", "");
            }
            this.$store.state.user.homestayIdArr = res.data.data;
            localStorage.setItem(
              "homestayIdArr",
              JSON.stringify(res.data.data)
            );
            localStorage.setItem(
              "homestayId",
              this.$store.state.user.homestayId
            );
            //账单明细和财务概况酒店民宿用到
            localStorage.setItem(
              "MerchantId",
              this.$store.state.user.homestayId
            );
            localStorage.setItem(
              "homestayName",
              this.$store.state.user.homestayName
            );
            resolve();
          }
        });
      });
    },
    getMerchantId() {
      return new Promise((resolve, reject) => {
        this.$http
          .get("/scenic/merchant/info/getUserMerchantList")
          .then((res) => {
            if (res.data.code == 0) {
              if (res.data.data[0]) {
                if (res.data.data.length > 0) {
                  this.$store.state.user.MerchantIdArr = res.data.data;
                  this.$store.state.user.MerchantId = res.data.data[0].id || "";
                  this.$store.state.user.MerchantName =
                    res.data.data[0].name || "";
                  localStorage.setItem(
                    "ss_merchantCategory",
                    res.data.data[0].merchantCategory || ""
                  );
                  this.idName = res.data.data[0].id;
                } else {
                  this.$store.state.user.MerchantIdArr = [];
                  this.$store.state.user.MerchantId = "";
                  this.$store.state.user.MerchantName = "";
                  localStorage.setItem("ss_merchantCategory", "");
                }
                localStorage.setItem(
                  "MerchantIdArr",
                  JSON.stringify(res.data.data)
                );
                localStorage.setItem(
                  "MerchantId",
                  this.$store.state.user.MerchantId
                );
                localStorage.setItem(
                  "MerchantName",
                  this.$store.state.user.MerchantName
                );
              }
              resolve();
            }
          });
      });
    },
    // 获取当前管理员信息
    getUserInfo() {
      return this.$http
        .get("/sys/user/info")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$store.state.user.id = res.data.id;
          this.$store.state.user.name = res.data.username;
          this.$store.state.user.realName = res.data.realName;
          this.$store.state.user.superAdmin = res.data.superAdmin;
          this.$store.state.user.roleList = res.data.roleIdList;
          this.$store.state.user.typelist = res.data.typeList;
          // if (res.data.superAdmin == 1) {
          //     this.$router.replace({
          //         name: "home"
          //     });
          // }
        })
        .catch(() => {});
    },
    // 获取权限
    getPermissions() {
      return this.$http
        .get("/sys/menu/permissions")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          localStorage.setItem("permissionsListArr", JSON.stringify(res.data));
          if (res.data[this.idName]) {
            window.SITE_CONFIG["permissions"] = res.data[this.idName];
          } else {
            window.SITE_CONFIG["permissions"] = res.data[-1];
          }
          localStorage.setItem(
            "currentPermissions",
            JSON.stringify(window.SITE_CONFIG["permissions"])
          );
        })
        .catch(() => {});
    },
    fnAddDynamicMenuRoutes(menuList = [], routes = []) {
      var temp = [];
      for (var i = 0; i < menuList.length; i++) {
        if (menuList[i].children && menuList[i].children.length >= 1) {
          temp = temp.concat(menuList[i].children);
          continue;
        }
        // 组装路由
        var route = {
          path: "",
          component: null,
          name: "",
          meta: {
            ...window.SITE_CONFIG["contentTabDefault"],
            menuId: menuList[i].id,
            title: menuList[i].name,
          },
        };
        // eslint-disable-next-line
        let URL = (menuList[i].url || "").replace(/{{([^}}]+)?}}/g, (s1, s2) =>
          eval(s2)
        ); // URL支持{{ window.xxx }}占位符变量
        if (isURL(URL)) {
          route["path"] = route["name"] = `i-${menuList[i].id}`;
          route["meta"]["iframeURL"] = URL;
        } else {
          URL = URL.replace(/^\//, "").replace(/_/g, "-");
          route["path"] = route["name"] = URL.replace(/\//g, "-");
          route["component"] = () => import(`@/views/modules/${URL}`);
        }
        routes.push(route);
        this.show = true;
      }
      if (temp.length >= 1) {
        return this.fnAddDynamicMenuRoutes(temp, routes);
      }
      const moduleRoutes = {
        path: "/",
        component: () => import("@/views/main"),
        name: "main",
        redirect: { name: "home" },
        meta: { title: "主入口布局" },
        children: [
          {
            path: "/home",
            component: () => import("@/views/modules/home"),
            name: "home",
            meta: { title: "首页", isTab: true },
          },
          {
            path: "/iframe",
            component: null,
            name: "iframe",
            meta: { title: "iframe", isTab: true },
          },
          {
            path: "/priceSetList",
            component: () => import("@/views/modules/roomManage/priceSetList"),
            name: "priceSetList",
            meta: { title: "批量定价" },
          },
           {
            path: "/roomShape-concatLink",
            component: () => import("@/views/modules/roomManage/roomShape-concatLink"),
            name: "roomShape-concatLink",
            meta: { title: "携程房型映射" },
          },
        ],
      };
      // 添加路由
      this.$router.addRoutes([
        {
          ...moduleRoutes,
          name: "main-dynamic-menu",
          children: routes,
        },
        { path: "*", redirect: { name: "404" } },
      ]);
      window.SITE_CONFIG["dynamicMenuRoutes"] = routes;
      window.SITE_CONFIG["dynamicMenuRoutesHasAdded"] = true;
    },
  },
};
</script>
